#!/bin/sh

# 环境变量设置
source ~/.vis_profile

# start services.
start()
{
    # 目录准备
    mkdir -p ${VIS_LOG_PATH}
    mkdir -p ${VIS_FILE_ROOT_PATH}/flv
    mkdir -p ${VIS_FILE_ROOT_PATH}/mp4
    mkdir -p ${VIS_FILE_ROOT_PATH}/hls
    mkdir -p ${VIS_FILE_ROOT_PATH}/live
    mkdir -p ${VIS_FILE_ROOT_PATH}/thumbnail
    
    # 配置文件准备
    cp -f ${VIS_ROOT_PATH}/srs/conf/srs.conf.template ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{VIS_ROOT_PATH}#${VIS_ROOT_PATH}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{VIS_LOG_PATH}#${VIS_LOG_PATH}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{NGINX_HTTP_PORT}#${NGINX_HTTP_PORT}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{RESTFUL_HTTP_PORT}#${RESTFUL_HTTP_PORT}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{VIS_FILE_ROOT_PATH}#${VIS_FILE_ROOT_PATH}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{VIS_UPLOAD_PATH}#${VIS_UPLOAD_PATH}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{SRS_RTMP_PORT}#${SRS_RTMP_PORT}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    sed -i "s#{SRS_HTTP_PORT}#${SRS_HTTP_PORT}#g" ${VIS_ROOT_PATH}/srs/conf/srs.conf
    
    # 启动
    cd ${VIS_ROOT_PATH}/srs
    ./etc/init.d/srs.sh start > ${VIS_LOG_PATH}/srs.log 2>/dev/null &
}

stop()
{
    # 停止
    cd ${VIS_ROOT_PATH}/srs
    ./etc/init.d/srs.sh stop > ${VIS_LOG_PATH}/srs.log 2>/dev/null &
}

restart()
{
    # 重启
    PIDS=`ps -ef | egrep "./objs/srs -c ./conf/srs.conf" | grep -v "grep" | awk '{print $2}'`
    if [ -z "$PIDS" ]
    then
        start
    else
        cd ${VIS_ROOT_PATH}/srs
        ./etc/init.d/srs.sh reload > ${VIS_LOG_PATH}/srs.log 2>/dev/null &
    fi
}

RETVAL=0
# execute parameter:
#  @$1  start|stop|restart|...
#  @$2  shell file name.
execute()
{
    case "$1" in
        start)
            start
        ;;
        
        stop)
            stop
        ;;
        
        restart)
            restart
        ;;
        
        *)
            echo $"Usage: $2 {start|stop|restart|reload|status}"
            RETVAL=1
            exit $RETVAL
    esac
}

# execute shell file.
execute "$1" "$0"

RETVAL=$?

exit $RETVAL
